import { Request, Response } from 'express';
import { homeModuleService } from './service';
import { AuthRequest } from '../../types/auth';
import { ApiResponse } from '../../types/page';
import { HomeModule, HomeModuleType } from '../../entities/HomeModule';

type HomeModuleListResponse = {
  records: HomeModule[];
  total: number;
  size: number;
  current: number;
  pages: number;
};

/**
 * 获取首页模块列表
 */
export const getHomeModules = async (req: AuthRequest, res: Response) => {
  try {
    const current = Number(req.query.page) || 1;
    const size = Number(req.query.size) || 10;
    const type = req.query.type !== undefined ? Number(req.query.type) : undefined;
    const isActive = req.query.isActive !== undefined ? req.query.isActive === 'true' : undefined;
    const moduleName = req.query.moduleName as string;
    
    const { modules, total } = await homeModuleService.getHomeModules({
      page: current,
      pageSize: size,
      type,
      isActive,
      moduleName
    });
    
    const response: ApiResponse<HomeModuleListResponse> = {
      success: true,
      data: {
        records: modules,
        total,
        size,
        current,
        pages: Math.ceil(total / size)
      }
    };
    
    res.json(response);
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取首页模块列表失败',
      error: error.message
    });
  }
};

/**
 * 获取首页模块详情
 */
export const getHomeModuleDetail = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const module = await homeModuleService.getHomeModuleById(id);
    
    if (!module) {
      return res.status(404).json({
        success: false,
        message: '首页模块不存在'
      });
    }
    
    res.json({
      success: true,
      data: module
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '获取首页模块详情失败',
      error: error.message
    });
  }
};

/**
 * 创建首页模块
 */
export const createHomeModule = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const moduleData = req.body;

    console.log(moduleData);
    
    // 验证必填字段
    if (!moduleData.type || !moduleData.moduleName) {
      return res.status(400).json({
        success: false,
        message: '类型、模块名称必填项'
      });
    }
    
    // 验证类型是否有效
    if (!Object.values(HomeModuleType).includes(moduleData.type)) {
      return res.status(400).json({
        success: false,
        message: '无效的模块类型'
      });
    }
    
    const module = await homeModuleService.createHomeModule(moduleData, userId);
    
    res.json({
      success: true,
      message: '创建首页模块成功',
      data: module
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '创建首页模块失败',
      error: error.message
    });
  }
};

/**
 * 更新首页模块
 */
export const updateHomeModule = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const id = req.params.id;
    const moduleData = req.body;
    
    // 验证类型是否有效
    if (moduleData.type && !Object.values(HomeModuleType).includes(moduleData.type)) {
      return res.status(400).json({
        success: false,
        message: '无效的模块类型'
      });
    }
    
    const module = await homeModuleService.updateHomeModule(id, moduleData, userId);
    
    if (!module) {
      return res.status(404).json({
        success: false,
        message: '首页模块不存在'
      });
    }
    
    res.json({
      success: true,
      message: '更新首页模块成功',
      data: module
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '更新首页模块失败',
      error: error.message
    });
  }
};

/**
 * 删除首页模块
 */
export const deleteHomeModule = async (req: AuthRequest, res: Response) => {
  try {
    const id = req.params.id;
    const result = await homeModuleService.deleteHomeModule(id);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '首页模块不存在或删除失败'
      });
    }
    
    res.json({
      success: true,
      message: '删除首页模块成功'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '删除首页模块失败',
      error: error.message
    });
  }
};

/**
 * 更新模块状态
 */
export const updateModuleStatus = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const id = req.params.id;
    const { isActive } = req.body;
    
    if (typeof isActive !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: '状态参数无效'
      });
    }
    
    const result = await homeModuleService.updateModuleStatus(id, isActive, userId);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '首页模块不存在或更新失败'
      });
    }
    
    res.json({
      success: true,
      message: `${isActive ? '启用' : '禁用'}首页模块成功`
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '更新模块状态失败',
      error: error.message
    });
  }
};

/**
 * 更新模块排序
 */
export const updateModuleSort = async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.user?.id;
    if (!userId) {
      return res.status(401).json({
        success: false,
        message: '用户未登录'
      });
    }
    
    const id = req.params.id;
    const { sortOrder } = req.body;
    
    if (typeof sortOrder !== 'number' || sortOrder < 0) {
      return res.status(400).json({
        success: false,
        message: '排序号必须是非负整数'
      });
    }
    
    const result = await homeModuleService.updateModuleSort(id, sortOrder, userId);
    
    if (!result) {
      return res.status(404).json({
        success: false,
        message: '首页模块不存在或更新失败'
      });
    }
    
    res.json({
      success: true,
      message: '更新模块排序成功'
    });
  } catch (error: any) {
    res.status(500).json({
      success: false,
      message: '更新模块排序失败',
      error: error.message
    });
  }
}; 